import settings
import traceback
import requests
import json
from bot.insurance_planner_gpt.interface.base_handler import BaseHandler
from common.log import logger


class GetWxInfoHandler(BaseHandler):

    def get(self):
        try:
            self.set_default_headers()
            # 获取小程序登录凭证 code
            code = self.get_argument('code', '')

            # 向微信服务器发送请求，获取用户的 session_key 和 openid
            appid = settings.WX_APPID
            secret = settings.WX_SECRET
            url = f'https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code'

            response = requests.get(url)
            data = response.json()

            logger.info(f"微信响应内容为:{data}")

            # 处理返回的数据，获取 session_key 和 openid
            session_key = data.get('session_key')
            openid = data.get('openid')

            # 返回自定义的响应数据给小程序
            self.write(json.dumps({'message': '登录成功', 'openid': openid}))
        except Exception as ee:
            logger.error(traceback.format_exc())
            self.write(
                json.dumps({'message': '系统异常', 'openid': None}))
